package com.mdp.tpa.pay.alipay.service;


import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.mdp.core.err.BizException;
import com.mdp.meta.client.entity.ItemVo;
import com.mdp.meta.client.service.ItemService;
import com.mdp.tpa.pay.wxpay.service.WxpayNativeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.UUID;

/*
 * 支付宝相关功能
 * author zhw
 */
@Service
public class AlipayService {

    private Logger log= LoggerFactory.getLogger(AlipayService.class);

    public String gateway="https://openapi.alipay.com/gateway.do";
    public String appid="2021002173608161";
    public String pubKey="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA42iH9W9D0xaYF48LqTy5mDzmcaS4ZQikxp7+fCfKc6a7ZDzruVmwqE11gAdaLIe6+QZqI65mDCmxLWN0q6MjJ2weAn1xdz6CAb8sVS5Ap7pk1eAE+7Pd7VGmv5tSOdVOd47HGVZ+cydBVY3oOOdcmodjU2WLwgznKUxYGWwxuO4R28v3WZkPOzDzolDhPk8DTbB/aG/cGIJluXNuCe4kkyou64G+mJy7vxFycbieZh1xfYxtp5g2qHyQkGXh8Vc9jttZlaAYHQtB0kmCBxiVqL+JipBM28sy63e7w1qMJw2Sub5RlF8fo1sBvNgSL1WVv6iIjOm+q+48uNXj2YzYYwIDAQAB";
    public String primaryKey="MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCdxJfveL3H9WbjCbXEfPGOFFbu1evsFAwMA7hMAEBhEUw1RIacNhNmkPuAgnI/2ZVplTIvdcT/Htvv/X4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LDhLB9ZoFd2L46Wxcfl8B46Bq8f/csZbLrUQKBgE3MPbPpcweemSoWuY02bKKBi6oqQN/BHrdfMNMj888AKuwi6utcV6fVtSjPCVZ0/b6x7VDDeITtKAZ3NOCQRuNh1khKZ7Mw7Y0QBUqEpDByoVBesaktQaYXZ7K7xgMqSYsOQAETv8qhm1JxClXjS1yXAVx8R2O50bBdNfWVRlPVAoGALWtH2X5N0mqF/Dpjku306hgUKfh5CG3EDh3i7iU9hycnoqt2D+rhgQRbDN8sG0WfBQpd1o1cRcYPFLDnEeLCFYm0VZfg6pt79i14STyMp7mw/pEmisWzW5N4zmeiejzNYQv+5Fp5CB8Ft0gUaug+5MnFCyka9LGf6I91BSEGoDQ=";
//    public String notifyUrl="https://www.qingqinkj.com/api/wzsc/mall/mall/tpa/alipay/notify";
    public String notifyUrl="https://www.qingqinkj.com/api/m1/tpa/pay/alipay/notify";


    @Autowired
    ItemService itemService;

    public AlipayTradePagePayResponse uniOrder(String otype,String outTradeNo,String payId, BigDecimal totalAmount, String subject, String returnUrl){

        AlipayClient alipayClient = this.alipayClient();
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setNotifyUrl(notifyUrl);
        request.setReturnUrl(returnUrl);
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", outTradeNo);
//        bizContent.put("total_amount", totalAmount.setScale(2, BigDecimal.ROUND_HALF_UP));
        bizContent.put("total_amount", totalAmount);
        bizContent.put("subject", StringUtils.hasText(subject)?subject:outTradeNo);
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
        //bizContent.put("time_expire", "2022-08-01 22:00:00");
        //// 商品明细信息，按需传入
        //JSONArray goodsDetail = new JSONArray();
        //JSONObject goods1 = new JSONObject();
        //goods1.put("goods_id", "goodsNo1");
        //goods1.put("goods_name", "子商品1");
        //goods1.put("quantity", 1);
        //goods1.put("price", 0.01);
        //goodsDetail.add(goods1);
        //bizContent.put("goods_detail", goodsDetail);
        JSONObject attach=new JSONObject();
        attach.put("otype",otype);
        attach.put("payId", payId);
        bizContent.put("passback_params", attach.toJSONString());

        request.setBizContent(bizContent.toString());
        AlipayTradePagePayResponse response = null;
        try {
            response = alipayClient.pageExecute(request);
        } catch (AlipayApiException e) {
            throw new BizException("下单失败",e.getErrMsg());
        }
        return response;

    }

    public AlipayClient alipayClient(){
        ItemVo itemVo=itemService.getDict("sysParam","alipaySet");
        gateway=itemVo.getExtInfo("gateway").getValue();
        appid=itemVo.getExtInfo("appid").getValue();
        primaryKey=itemVo.getExtInfo("primaryKey").getValue();
        pubKey=itemVo.getExtInfo("pubKey").getValue();
        notifyUrl=itemVo.getExtInfo("notifyUrl").getValue();
        AlipayClient alipayClient = new DefaultAlipayClient(gateway,appid,primaryKey,"json","UTF-8",pubKey,"RSA2");
        return alipayClient;
    }

    public AlipayTradeQueryResponse tradeQuery(String orderId) throws AlipayApiException {
        AlipayClient alipayClient = this.alipayClient();
         AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();//创建API对应的request类
        request.setBizContent("{" +
                "\"out_trade_no\":\""+orderId+"\"}"); //设置业务参数
        try {
            AlipayTradeQueryResponse response = alipayClient.execute(request);//通过alipayClient调用API，获得对应的response类
            return response;
        } catch (AlipayApiException e) {
            log.error("",e);
            throw e;
        }

        //根据response中的结果继续业务逻辑处理
    }
}
